package com.fz.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-08.
 */
@Controller
public class smvcxiazai {

    @RequestMapping("/smvcxiazai")
    public ResponseEntity<byte[]> download(HttpServletRequest req,  String fn) throws IOException {
        String fileName=fn;
        //下载之后重新给他命名
        String downname=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        //要下载的文件的路径
        //如果要想让别人知道路径也没办法下载，就放在WEB-INF下面
        //String path=req.getServletContext().getRealPath("/download/");
        String path=req.getServletContext().getRealPath("/WEB-INF/download/");
        //这个流是读取要下载的文件
        InputStream is=new FileInputStream(path+"/"+fileName);
        byte[] buf=new byte[is.available()];
        is.read(buf);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + downname);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buf, headers, statusCode);
        return entity;
    }
}
